package com.coinworld.utils;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

@Slf4j
public class JSONUtils {

    private static final ObjectMapper MAPPER = new ObjectMapper();

    /**
     *
     */
    private JSONUtils() {
    }

    public static String writeString(Object o) {
        if (o != null) {
            try {
                return MAPPER.writeValueAsString(o);
            } catch (JsonProcessingException ignored) {
                log.error("JSONUtils writeString exception {}", ignored);
            }
        }
        return "";
    }

    public static <T> T readValue(String json, JavaType javaType) {
        if (StringUtils.isNotEmpty(json)) {
            try {
                return MAPPER.readValue(json, javaType);
            } catch (IOException ignored) {
                log.error("JSONUtils readValue exception {}", ignored);
            }
        }
        return null;
    }

    public static <T> T readValue(String json, Class<T> clazz) {
        if (StringUtils.isNotEmpty(json)) {
            try {
                return MAPPER.readValue(json, clazz);
            } catch (IOException ignored) {
                log.error("JSONUtils readValue exception {}", ignored);
            }
        }
        return null;
    }

    public static <T> List<T> readListValue(String json, Class<T> clazz) {
        if (StringUtils.isNotEmpty(json)) {
            JavaType javaType = MAPPER.getTypeFactory().constructParametricType(ArrayList.class, clazz);
            try {
                return  MAPPER.readValue(json, javaType);
            } catch (IOException ignored) {
                log.error("JSONUtils readListValue exception {}", ignored);
            }
        }
        return null;
    }
}
